package com.zerocarbon.framework.db.config;

import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.core.parser.SqlParserHelper;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.zerocarbon.framework.core.context.UserContextHandler;
import com.zerocarbon.framework.db.properties.DatabaseProperties;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.ibatis.mapping.MappedStatement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 多租户自动配置
 * @author wyf
 * @date 2020年3月5日
 */
@Configuration
@EnableConfigurationProperties(DatabaseProperties.class)
public class TenantAutoConfigure {
	
    @Autowired
    private DatabaseProperties databaseProperties;

    /**
     * 多租户（字段）
     * @return
     */
    @Bean
    public TenantHandler tenantHandler() {
    	//log.info("---------------------------18 多租户自动配置 TenantHandler init----------------------------------------");
        return new TenantHandler() {
            /**
             * 获取租户id
             */
            @Override
            public Expression getTenantId(boolean where) {
                //String tenant = TenantContextHolder.getTenant();
            	Long tenantId = UserContextHandler.getTenantId();
                if (tenantId != null) {
                    return new StringValue(tenantId.toString());
                }
                return new NullValue();
            }

            /**
             * 获取租户列名
             */
            @Override
            public String getTenantIdColumn() {
                return databaseProperties.getTenant().getTenantIdColumn();
            }

            /**
             * 过滤不需要根据租户隔离的表
             * @param tableName 表名
             */
            @Override
            public boolean doTableFilter(String tableName) {
                return databaseProperties.getTenant().getIgnoreTables().stream().anyMatch((e) -> e.equalsIgnoreCase(tableName));
            }
        };
    }

    /**
     * 过滤不需要根据租户隔离的MappedStatement
     */
    @Bean
    public ISqlParserFilter sqlParserFilter() {
        return metaObject -> {
            	MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject);
            	return databaseProperties.getTenant().getIgnoreSqls().stream().anyMatch((e) -> e.equalsIgnoreCase(ms.getId())
            );
        };
    }
}
